# -*- coding: UTF-8 -*- #
"""
-------真正的勇士， 敢于直面惨淡的Warning、 敢于正视淋漓的Error-----
@author : 贾鹏博
@file : mysql_utils.py
@time : 2022/5/8 16:39
"""

import pymysql
import sys


class Mc():
    def __int__(self, db_host='10.85.50.31', username='root', password='123456', port=3306, db_name='sojo_eap'):
        self.db_host = db_host
        self.username = username
        self.password = password
        self.db_name = db_name
        self.port = port
        self.db = pymysql.connect(self.db_host, self.username, self.password, self.db_name, self.port,
                                  charset='utf8mb4')

    # 插入数据语句
    def insertDB(self, sql):
        self.cursor = self.db.cursor()
        try:
            # 执行sql
            self.cursor.execute(sql)
            self.db.commit()
        except:
            # 发生错误时回滚
            self.db.rollback()
        finally:
            self.cursor.close()

    # 删除数据语句
    def deleteDB(self, sql):
        self.cursor = self.db.cursor()
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
        finally:
            self.cursor.close()

    # 更新数据语句
    def updateDB(self, sql):
        self.cursor = self.db.cursor()
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
        finally:
            self.cursor.close()

    # 查询数据
    def seleteDB(self, sql):
        self.cursor = self.db.cursor()
        try:
            self.cursor.execute(sql)
            # 返回所有结果
            data = self.cursor.fetchall()
        except:
            print('Error: unable to fecth data')
        finally:
            self.cursor.close()
        return data

    def closeDB(self):
        self.db.close()
